<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>实时监控PUT-QPS</title>
  <script src="https://gw.alipayobjects.com/os/lib/antv/g2/4.0.7/dist/g2.min.js"></script>
</head>
<body>
<p>QPS统计</p>
<br>
<div id='container' style="margin: 10px"/>
</body>

<script>

  Date.prototype.format = function(fmt) {
       var o = {
          "M+" : this.getMonth()+1,                 //月份
          "d+" : this.getDate(),                    //日
          "h+" : this.getHours(),                   //小时
          "m+" : this.getMinutes(),                 //分
          "s+" : this.getSeconds(),                 //秒
          "q+" : Math.floor((this.getMonth()+3)/3), //季度
          "S"  : this.getMilliseconds()             //毫秒
      };
      if(/(y+)/.test(fmt)) {
              fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
      }
       for(var k in o) {
          if(new RegExp("("+ k +")").test(fmt)){
               fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
           }
       }
      return fmt;
  }
  /**
   * 创建图表.
   * @param storage
   * @returns {G2.Chart}
   */
  function createChart(container, storage) {
    let chart = new G2.Chart({
      container: container,
      autoFit: false,
      height: 300,
      width: 1000
    });

    chart.scale({
      year: {
      },
      value: {
        min: 0,
        nice: true,
      },
    });
    chart.tooltip({
      title: '当前QPS',
      showCrosshairs: true, // 展示 Tooltip 辅助线
      shared: true,
    });
    chart.data(storage);
    chart
      .path()
      .position('year*value')

    chart.option('slider', {
      end: 1.0
    });
    chart.render();
    return chart;
  }

  const requestCounters = {};
  const storage = [{
    "year": new Date().format("mm:ss"),
    "value": 0
  }];
  const chart = createChart('container',storage);
  // 定时任务
  setInterval(countUp, 1000);

  function countUp() {
    let date = new Date().format("mm:ss");
    fetch('./data', {method: 'PATCH'})
      .then(res => res.json())
      .then(data => {
        if (storage.length > 240) {
          storage.shift();
        }
        storage.push({
          "year": date,
          "value": data["vertx.http.servers.0.0.0.0:8082.put-requests"]["oneSecondRate"],
        });
        chart.changeData(storage);
        for (var key in data) {
          if (key.includes("-requests")) {
            let cat = key.slice(key.lastIndexOf(".") + 1).replace("-requests", "").toLocaleUpperCase();
            requestCounters[cat] = data[key]["count"];
          }
        }
      });
  }
</script>
</html>
